package com.duguyuan.client;

import com.duguyuan.utils.MessageProtocol;

import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.net.Socket;
import java.util.HashMap;

public class ClientService implements Client {

    String serverIPAddress = MessageProtocol.DEFAULT_SERVER_IP_ADDRESS;
    int serverPort = MessageProtocol.DEFAULT_SERVER_PORT;

    private LoginFrame loginFrame;
    ClientFrame clientFrame;

    private Socket socket;
    private BufferedReader bufferedReader;
    private BufferedWriter bufferedWriter;
    HashMap<String, String> chattingRecords;
    String username;
    String chatObject;

    public ClientService(LoginFrame loginFrame) {
        this.loginFrame = loginFrame;
    }

    /**
     * 客户端连接服务器方法
     */
    public void initConnection() {
        try {
            if (socket == null) {
                socket = new Socket(loginFrame.ipAddressTextField.getText(), Integer.parseInt(loginFrame.portTextField.getText()));
                loginFrame.ipAddressTextField.setEditable(false);
                loginFrame.portTextField.setEditable(false);
                if(bufferedReader == null || bufferedWriter == null) {
                    this.bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "utf-8"));
                    this.bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "utf-8"));
                }
                new Thread() {
                    @Override
                    public void run() {
                        String line = null;
                        try {
                            while((line = bufferedReader.readLine()) != null) {
                                if (MessageProtocol.LOGIN_SUCCESS.equals(line)) { // 登录成功
                                    username = loginFrame.usernameTextField.getText();
                                    new ClientFrame(ClientService.this);
                                    loginFrame.dispose();
                                    break;
                                }else {
                                    JOptionPane.showMessageDialog(loginFrame, line, "客户端消息提示", JOptionPane.INFORMATION_MESSAGE);
                                }
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(loginFrame, "登录发生异常，即将退出", "客户端消息提示", JOptionPane.ERROR_MESSAGE);
            System.exit(0);
        }
    }

    /**
     * 客户端发送注册或登录信息的方法
     * @param type
     * @param message
     * @throws IOException
     */
    public void sendMessage(String type, String message) throws IOException {
        bufferedWriter.write( type + message + type);
        bufferedWriter.newLine();
        bufferedWriter.flush();
    }

    /**
     * 客户端初始化方法
     */
    public void initClient() {
        try {
            if(bufferedReader == null || bufferedWriter == null) {
                this.bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "utf-8"));
                this.bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "utf-8"));
            }
            new Thread() {
                @Override
                public void run() {
                    String line = null;
                    try {
                        while((line = bufferedReader.readLine()) != null) {
                            if(line.startsWith(MessageProtocol.ADD_USER) && line.endsWith(MessageProtocol.ADD_USER)) {
                                addUser(getRealMessage(line));
                            }else if (line.startsWith(MessageProtocol.DELETE_USER) && line.endsWith(MessageProtocol.DELETE_USER)) {
                                deleteUser(getRealMessage(line));
                            }else if (line.startsWith(MessageProtocol.PRIVATE_ROUND) && line.endsWith(MessageProtocol.PRIVATE_ROUND)) {
                                // 私聊处理操作
                                String realMessage = getRealMessage(line);
                                String username = realMessage.split(MessageProtocol.SEPARATOR)[0];
                                String message = realMessage.split(MessageProtocol.SEPARATOR)[1];
                                chattingRecords.put(username, chattingRecords.get(username) + "【" + username + "】说: " + message + "\n");
                                if (username.equals(chatObject)) {
                                    clientFrame.chatViewTextArea.append("【" + username + "】说: " + message + "\n");
                                } else {
                                    clientFrame.myRenderer.setRowColor(clientFrame.usersListModel.indexOf(username), Color.RED);
                                    clientFrame.repaint();
                                }
                            }else if (line.startsWith(MessageProtocol.PUBLIC_ROUND) && line.endsWith(MessageProtocol.PUBLIC_ROUND)) {
                                String message = getRealMessage(line);
                                chattingRecords.put("多人聊天室", chattingRecords.get("多人聊天室") + message + "\n");
                                if ("多人聊天室".equals(chatObject)) {
                                    clientFrame.chatViewTextArea.append(message + "\n");
                                }else {
                                    clientFrame.myRenderer.setRowColor(clientFrame.usersListModel.indexOf("多人聊天室"), Color.RED);
                                    clientFrame.repaint();
                                }
                            }
                        }
                    } catch (IOException e) {
                        // e.printStackTrace();
                        JOptionPane.showMessageDialog(clientFrame, "服务器异常，客户端即将退出", "客户端消息提示", JOptionPane.ERROR_MESSAGE);
                        System.exit(0);
                    }
                }
                /**
                 * 将读到的内容去掉前后的协议字符，恢复成真实数据
                 * @param line
                 * @return
                 */
                public String getRealMessage(String line) {
                    return line.substring(MessageProtocol.PROTOCOL_LENGTH, line.length() - MessageProtocol.PROTOCOL_LENGTH);
                }
            }.start();
            // 提示登录成功
            JOptionPane.showMessageDialog(clientFrame, MessageProtocol.LOGIN_SUCCESS, "客户端消息提示", JOptionPane.INFORMATION_MESSAGE);
            // 同步用户列表
            sendMessage(MessageProtocol.SYN_USER + "同步用户列表" + MessageProtocol.SYN_USER);
        } catch (IOException e) {
            // e.printStackTrace();
            JOptionPane.showMessageDialog(clientFrame, "客户端发生异常，客户端即将退出", "客户端消息提示", JOptionPane.ERROR_MESSAGE);
            System.exit(0);
        }
    }

    /**
     * 客户端发送聊天消息的方法
     * @param type
     * @throws IOException
     */
    public void sendMessage(String type) throws IOException {
        String message = clientFrame.chatTextField.getText();
        if (MessageProtocol.PRIVATE_ROUND.equals(type)) {
            if (!chatObject.equals(username)) {
                chattingRecords.put(chatObject, chattingRecords.get(chatObject) + "【我】说: " + message + "\n");
                clientFrame.chatViewTextArea.append("【我】说: " + message + "\n");
            }
            message = chatObject + MessageProtocol.SEPARATOR + message;
        }
        bufferedWriter.write( type + message + type);
        bufferedWriter.newLine();
        bufferedWriter.flush();
        clientFrame.chatTextField.setText("");
    }


    @Override
    public void addUser(String username) {
        clientFrame.usersListModel.addElement(username);
        chattingRecords.put(username, "");
    }

    @Override
    public void deleteUser(String username) {
        clientFrame.usersListModel.removeElement(username);
        chattingRecords.remove(username);
    }

}
